import { Card, Col, DatePicker, Form, Input, message, Modal, Row, Select, type DatePickerProps } from "antd";
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import '../ArrangeInterviewForm/index.scss'
import type { ArrangeInterview, ArrangeInterviewFormProps, candidateFormProps, OptionType, User} from "@/types";
import { arrangeInterview } from "@/apis/interview";
import { getInterviewOptions } from "@/apis/commonService"
import { filterOptionsByOptionGroupKey } from "@/utils/common";
import { queryCandidateByIds } from "@/apis/candidate";
import type { RangePickerProps } from "antd/es/date-picker";
import SelectUserModal from "../SelectUserModal";
import dayjs, { Dayjs } from "dayjs";


const ArrangeInterviewForm = forwardRef((props: candidateFormProps, ref) => {
    // 表单标识
    const [form] = Form.useForm();
    // 面试方式选项
    const [interviewWayList,setInterviewWayList] = useState<OptionType[]>([]);
    // 面试类别选项
    const [interviewCategoryList,setInterviewCategoryList] = useState<OptionType[]>([]);
    // 面试时长选项
    const [interviewDurationList,setInterviewDurationList] = useState<OptionType[]>([]);
    // 选择面试官弹窗组件标识
    const selectUserModalRef = useRef(null);

    // 安排面试信息
    const [arrangeInterviewForm,setArrangeInterviewForm] = useState<ArrangeInterviewFormProps>({
        interviewerIdList: [],
        candidateList: [],
    });
    
    const [isModalOpen, setIsModalOpen] = useState(false);
      const handleOk = async () => {
        await form.validateFields();
        const params: ArrangeInterview = {
            title: form.getFieldValue('title'),
            interviewWayId: form.getFieldValue('interviewWayId'),
            interviewCategoryId: form.getFieldValue('interviewCategoryId'),
            receiverEmail: form.getFieldValue('receiverEmail'),
            carbonCopyEmail: form.getFieldValue('carbonCopyEmail'),
            interviewDate: form.getFieldValue('interviewDate').format('YYYY-MM-DD HH:mm:ss'),
            interviewDuration: form.getFieldValue('interviewDuration'),
            address: form.getFieldValue('address'),
            candidateIdList: arrangeInterviewForm.candidateList?.map(item => item.id) as string[],
            interviewerIdList: arrangeInterviewForm.interviewerIdList as string[]
        }
        console.log(params);
        // setIsModalOpen(false);
        const res = await arrangeInterview(params);
        console.log("res=====>",res);
        
        if (res.data.code === 200) {
            message.success('安排面试成功！');
            props.reQuery();
            setIsModalOpen(false);
        }else{
            message.error('安排面试失败！')
        }
        console.log("安排面试Res=========>",res);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const open = async (rows: string[]) => {
        console.log(rows);
        console.log("arrangeInterviewForm=======>",arrangeInterviewForm);
        // todo 根据传递的候选人id获取候选人数据并渲染到表单中
        const res = await queryCandidateByIds(rows);
        setArrangeInterviewForm({
            ...arrangeInterviewForm,
            interviewDate: dayjs(new Date()),
            candidateList: res.data
        })
        if (res.code === 200) {
            setIsModalOpen(true);
            InitInterviewOptions();
        }else {
            message.error(res.msg);
        }
    }

    // 更新表单信息
    useEffect(() => {
        form.setFieldsValue(arrangeInterviewForm);
    },[arrangeInterviewForm]);

    /** 初始化面试选项 */
    const InitInterviewOptions = async () => {
        const optionGroupKeys: string[] = ['interviewWay','interviewCategory','interviewDuration'];
        const res = await getInterviewOptions(optionGroupKeys);
        const allOptions: OptionType[] = res.data.data;
        setInterviewWayList(filterOptionsByOptionGroupKey(allOptions,'interviewWay'));
        setInterviewCategoryList(filterOptionsByOptionGroupKey(allOptions,'interviewCategory'));
        setInterviewDurationList(filterOptionsByOptionGroupKey(allOptions,'interviewDuration'));
    }

    /** 关闭弹窗的回调  */
    const closeHandle = () => {
        console.log("清除了表单回调");
        
        // 重置表单UI 只会清除页面UI上Form-item项绑定的数据，
        // 不会清除设置到ArrangeInterviewForm的数据 如：interviewerIdList、candidateList、interviewerList、interviewerNameStr
        // 设置到ArrangeInterviewForm的数据无法被form.resetFields()清除
        form.resetFields();
        
        // 重置所有业务状态
        setArrangeInterviewForm({
            interviewerIdList: [],
            candidateList: [],
            interviewerList: [],
            interviewerNameStr: ''
        });
        
        // 重置选项
        setInterviewWayList([]);
        setInterviewCategoryList([]);
        setInterviewDurationList([]);
    }

    /** 打开选择面试官弹窗  */
    const openSelectInterviewerPage = () => {
        selectUserModalRef.current.open(arrangeInterviewForm.interviewerList);
    }

    /** 选中用户回调  */
    const hanleSelectUser = (selectUserList: User[]) => {
        console.log("selectUserList=========>",selectUserList);
        setArrangeInterviewForm({
            ...arrangeInterviewForm,
            interviewerList: selectUserList,
            interviewerIdList: selectUserList.map(item => item.id) as string[],
            interviewerNameStr: selectUserList.map(item => item.name).join(',') as string
        });
    }

    /**
     * todo 
     * 1.点击选择面试官输入框时，弹出弹窗，弹窗中展示用户表格供勾选
     *  -- 弹出用户表格弹窗时，传入已选择的面试官id，进行跨页勾选
     *  -- 勾选完用户，并且点击确定关闭弹窗时，将勾选的用户信息返回
     *      -- 更新ArrangeInterview中的interviewerIdList
     *      -- 更新ArrangeInterview中的interviewerNameStr
     * 2.面试方式、面试类别、面试时长、面试地址 选项前后端配置
     *  -- 前端：配置选项的label和value
     *  -- 后端：创建选项表
     * 3.面试时间的组件框更换为dateTimePicker
     * 4.填写完安排面试信息后，点击对话框的确认按钮时
     *  -- 调用表单的字段校验
     *  -- 调用表单的onFinsh方法
     */

    useImperativeHandle(ref, () => ({
        open: open
    }));
    return <Modal
            afterClose={closeHandle}
            className="arrange-interview-form"
            title='安排面试'
            closable={{ 'aria-label': 'Custom Close Button' }}
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
            okText='确认'
            cancelText='取消'
            width={'80%'}
        >
        <Form
            form={form}
            layout="vertical"
            name="arrangeInterviewForm"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{  }}
            autoComplete="off"
        >
            <Card title={
                <div className="header">
                    {/* 职位基本信息展示 */}
                    <Row className="position-zone" align={'middle'}>
                        <Col span={24}>
                            <span style={{ color: '#8c8c8c' }}>应聘职位：</span>  
                            <span>开发工程师</span>  
                        </Col>
                    </Row>
                    {/* 候选人信息展示 */}
                    {
                        arrangeInterviewForm.candidateList?.map(item => {
                        return (
                            <Row className="candidate-zone" key={item.id}>
                                <Col span='2'>
                                    { item.name }
                                </Col>
                                <Col span='3'>
                                    <span style={{ color: '#8c8c8c' }}>手机号: </span>
                                    <span>{ item.contactNumber }</span>
                                </Col>
                                <Col span='3'>
                                    <span style={{ color: '#8c8c8c' }}>邮箱：</span>
                                    <span>330378686@qq.com</span>
                                </Col>
                            </Row>
                        )
                        })
                    }
                </div>
            } variant="borderless" style={{ width: '100%',marginTop: '15px' }}>
                <Row>
                    <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="面试标题"
                            name="title"
                        rules={[{ required: true, message: '请填写面试标题' }]}
                        >
                        <Input placeholder="请填写面试标题"/>
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="面试方式"
                            name="interviewWayId"
                        rules={[{ required: true, message: '请选择面试方式' }]}
                        >
                        <Select
                            options={interviewWayList}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="面试类别"
                            name="interviewCategoryId"
                        rules={[{ required: true, message: '请选择面试类别' }]}
                        >
                        <Select
                            options={interviewCategoryList}
                            />
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="接待人"
                            name="receiverEmail"
                        >
                        <Input placeholder="请填写接待人邮箱"/>
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="抄送人"
                            name="carbonCopyEmail"
                        >
                        <Input placeholder="请填写抄送人邮箱"/>
                        </Form.Item>
                    </Col>
                </Row>
            </Card>

            <Card title="面试信息" variant="borderless" style={{ marginTop: '20px' }}>
                <Row>
                    <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="面试官"
                            name="interviewerNameStr"
                            rules={[{ required: true, message: '请选择面试官' }]}
                        >
                        <Input readOnly onClick={() => openSelectInterviewerPage()} placeholder="请选择面试官" value={arrangeInterviewForm.interviewerNameStr}/>
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="面试时间"
                            name="interviewDate"
                            rules={[{ required: true, message: '请选择面试时间' }]}
                        >
                        <DatePicker
                            showTime
                            onChange={(value, dateString) => {
                                console.log('Selected Time: ', value);
                                console.log('Formatted Selected Time: ', dateString);
                            }}
                        />
                        </Form.Item>
                    </Col>
                     <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="面试时长"
                            name="interviewDuration"
                        rules={[{ required: true, message: '请选择面试时长' }]}
                        >
                        <Select
                            options={interviewDurationList}
                            />
                        </Form.Item>
                    </Col>
                     <Col span={6}>
                        <Form.Item<ArrangeInterviewFormProps>
                            label="面试地址"
                            name="address"
                            rules={[{ required: true, message: '请填写面试地址' }]}
                        >
                        <Input placeholder="请填写面试地址"/>
                        </Form.Item>
                    </Col>
                </Row>
            </Card>
        </Form>
        {/* 选择用户组件 */}
        <SelectUserModal title="选择面试官" ref={selectUserModalRef} hanleSelectUser={hanleSelectUser}></SelectUserModal>
        </Modal>
})

export default ArrangeInterviewForm;